import csv
import json

# 从JSON文件读取数据
def load_categories_from_json(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        return json.load(file)

# 初始化CSV数据列表
csv_data = []

# 从较高的数字开始ID计数，避免与现有系统分类ID冲突
category_id_counter = 1000  # 从1000开始，确保不会与现有分类ID冲突

def generate_description(category_name, parent_name):
    """根据分类名称生成更有意义的描述"""
    descriptions = {
        'Bags': 'Discover our exclusive collection of luxury bags from top designers.',
        'Shoes': 'Find the perfect pair of designer shoes for every occasion.',
        'Jewelry': 'Elegant and timeless jewelry pieces to complement your style.',
        'Accessories': 'Complete your look with our premium accessories collection.',
        'Watches': 'Luxury timepieces from the world\'s most prestigious watchmakers.',
        'New In': 'Check out our latest arrivals and newest luxury items.',
        'Louis Vuitton': 'Iconic Louis Vuitton bags and accessories with timeless design.',
        'Ch@nel': 'Elegant Chanel bags featuring classic designs and modern styles.',
        'Diro': 'Sophisticated Dior bags with exquisite craftsmanship and design.',
        'Hermès': 'Luxurious Hermès bags known for their exceptional quality and heritage.',
        'YSL': 'Chic Yves Saint Laurent bags combining elegance and contemporary style.',
        'Gucci': 'Trend-setting Gucci bags with iconic designs and Italian craftsmanship.',
        'Fendi': 'Luxurious Fendi bags with innovative designs and premium materials.',
        'Bottega Veneta': 'Sophisticated Bottega Veneta bags with exquisite weaving techniques.',
        'Loro Piana': 'Premium Loro Piana accessories known for exceptional fabric quality.',
        'Goyard': 'Heritage Goyard bags and trunks with distinctive patterns.',
        'Céline': 'Minimalist and elegant Celine bags for modern sophistication.',
        'Loewe': 'Artisanal Loewe bags with creative designs and craftsmanship.',
        'Balenciaga': 'Edgy Balenciaga bags with contemporary urban style.',
        'Miu miu': 'Playful and feminine Miu Miu bags with unique designs.'
    }
    
    if category_name in descriptions:
        return descriptions[category_name]
    elif 'Wallet' in category_name:
        return f'Luxury wallets and card holders from {parent_name if parent_name != "Home" else "top brands"}'
    elif 'Shoes' in category_name:
        return f'Designer shoes from {category_name.replace(" Shoes", "")} for sophisticated footwear'
    elif 'Bag' in category_name or 'bags' in category_name.lower():
        return f'Premium {category_name.lower()} collection for fashion enthusiasts'
    else:
        return f'Premium {category_name.lower()} collection for discerning tastes'

def process_category(category, parent_name="Home", depth=0):
    global category_id_counter
    
    # 确定是否为根分类
    is_root = 1 if depth == 0 else 0
    
    # 生成URL重写名称（从URL中提取或从名称生成）
    if 'url' in category:
        url_parts = [part for part in category['url'].split('/') if part]
        url_rewritten = url_parts[-1] if url_parts else category['name'].lower().replace(' ', '-')
    else:
        url_rewritten = category['name'].lower().replace(' ', '-').replace('&', 'and').replace('@', 'a')
    
    # 清理URL重写名称中的特殊字符
    url_rewritten = ''.join(c for c in url_rewritten if c.isalnum() or c in ['-', '_'])
    
    # 创建分类记录 - Image URL 设置为空
    category_record = {
        'Category ID': category_id_counter,
        'Active (0/1)': 1,
        'Name *': category['name'],
        'Parent category': parent_name,
        'Root category (0/1)': is_root,
        'Description': generate_description(category['name'], parent_name),
        'Meta title': f"{category['name']} | The Luxe Deals",
        'Meta description': f"Shop luxury {category['name'].lower()} at The Luxe Deals. Authentic designer items with premium quality.",
        'URL rewritten': url_rewritten,
        'Image URL': ''  # 设置为空字符串
    }
    
    csv_data.append(category_record)
    current_id = category_id_counter
    category_id_counter += 1
    
    # 递归处理子分类
    if 'children' in category:
        for child in category['children']:
            process_category(child, category['name'], depth + 1)
    
    return current_id

def main():
    global csv_data, category_id_counter
    
    # 从JSON文件加载数据
    try:
        json_data = load_categories_from_json('categories.json')
        print("成功从 categories.json 加载数据")
    except FileNotFoundError:
        print("错误: 找不到 categories.json 文件")
        return
    except json.JSONDecodeError:
        print("错误: categories.json 文件格式不正确")
        return
    
    # 重置计数器 - 从1000开始确保唯一性
    csv_data = []
    category_id_counter = 1000  # 从1000开始，避免与系统分类ID冲突
    
    # 处理所有顶级分类
    for category in json_data:
        process_category(category)
    
    # 写入CSV文件
    csv_filename = 'luxe_categories_import.csv'
    with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
        fieldnames = [
            'Category ID', 'Active (0/1)', 'Name *', 'Parent category', 
            'Root category (0/1)', 'Description', 'Meta title', 
            'Meta description', 'URL rewritten', 'Image URL'
        ]
        
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=';')
        writer.writeheader()
        
        for row in csv_data:
            writer.writerow(row)
    
    print(f"CSV文件已生成: {csv_filename}")
    print(f"共生成 {len(csv_data)} 个分类记录")
    
    # 显示统计信息
    root_categories = sum(1 for row in csv_data if row['Root category (0/1)'] == 1)
    sub_categories = len(csv_data) - root_categories
    
    print(f"根分类数量: {root_categories}")
    print(f"子分类数量: {sub_categories}")
    
    # 显示ID范围
    min_id = min(row['Category ID'] for row in csv_data)
    max_id = max(row['Category ID'] for row in csv_data)
    print(f"分类ID范围: {min_id} - {max_id}")
    
    # 检查ID唯一性
    all_ids = [row['Category ID'] for row in csv_data]
    unique_ids = set(all_ids)
    if len(all_ids) == len(unique_ids):
        print("✓ 所有分类ID都是唯一的")
    else:
        print("✗ 发现重复的分类ID")
    
    # 显示前几行作为预览
    print("\n前5行预览:")
    print("Category ID;Active (0/1);Name *;Parent category;Root category (0/1);Description;Meta title;Meta description;URL rewritten;Image URL")
    for i, row in enumerate(csv_data[:5]):
        print(f"{row['Category ID']};{row['Active (0/1)']};{row['Name *']};{row['Parent category']};{row['Root category (0/1)']};{row['Description']};{row['Meta title']};{row['Meta description']};{row['URL rewritten']};{row['Image URL']}")

if __name__ == "__main__":
    main()